package com.itheima.test;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.logging.log4j.util.Base64Util;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;

public class jwt {

    private static final String singKey = "TmFuWGlhblNlbl85NTI3"; //NanXianSen_9527 经过base64编码产生的结果


    private static final Long timeLimit = 1000L * 60 * 60 * 24;

    @Test
    // 生成jwt令牌
    public void generateJwt() {
        // System.out.println(" = " + Base64Util.encode("NanXianSen_9527")  );
        HashMap<String, Object> user = new HashMap<>();
        user.put("username", "nanxiansen");
        user.put("name", "小王");

        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, singKey)
                .addClaims(user)
                .setExpiration(new Date(System.currentTimeMillis() + timeLimit))
                .compact();

        System.out.println("token = " + token);

    }

//     校验jwt令牌

    @Test
    public void parseJWT() {
        String token ="eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5bCP546LIiwidXNlcm5hbWUiOiJuYW54aWFuc2VuIiwiZXhwIjoxNzQ2MDEyMzA5fQ.UIvpI_jN1ev3ZWmOYpNv8ZXQEDJahnsNr5WedMuD_uw";

        Claims body = Jwts.parser()
                .setSigningKey(singKey)
                .parseClaimsJws(token)
                .getBody();

        System.out.println("body = " + body);
    }
}
